$(function () {
    var couponCache = {};
    /**
     * 初始化红包列表
     */
    var initCouponTable = function () {
        chinese.sInfo = "共 _TOTAL_ 条";
        chinese.sInfoEmpty = "";
        var table = $('#couponList').DataTable({
            //"processing": true,
            //"serverSide": true,
            "sort": false,
            "search": false,
            "ajax": {
                "url": "pointsystem/listAuction",
//                "data": function (d) {
//                    //d.fundStatus = fundStatus.val();
//                },
                "type": "GET"
            },
            "aoColumnDefs": [{
                    "targets": 0,
                    "className": 'details-control',
                    "mRender": function (data, type, row) {
                        return '<span class="glyphicons glyphicons-circle_plus text-system cursor-pointer fs14"></span>';
                    }
                }, {
                    "targets": 1,
                    "mRender": function (data, type, row) {
                        return row.title;
                    }
                }, {
                    "targets": 2,
                    "mRender": function (data, type, row) {
                        return $.format.date(row.startTime, "yyyy/MM/dd HH:mm:ss");
                    }
                }, {
                    "targets": 3,
                    "mRender": function (data, type, row) {
                        return row.duration+ "小时";
                    }
                }, {
                    "targets": 4,
                    "mRender": function (data, type, row) {
                        return row.isDefault == '1' ? "是" : "否";
                    }
                },
                {
                    "targets": 5,
                    "mRender": function (data, type, row) {
                        var operations = $("#operationHTML").html().replace(/#id/g, row.id);
                        return operations;
                    }
                }],
            "order": [4, 'desc'],
            "oLanguage": chinese,
            "iDisplayLength": 10,
            "aLengthMenu": [
                [5, 10, 20, 50, 100, -1],
                [5, 10, 20, 50, 100, "全部"]
            ],
            "sDom": 't<"dt-panelfooter clearfix"lip>',
//             "sDom": '<"dt-panelmenu clearfix"l<"pull-right"T>r>t<"dt-panelfooter clearfix"ip>',
//            "oTableTools": {
//                "aButtons": [{
//                        "sExtends": "xls",
//                        "sButtonText": "导出为Excel"
//                    }
//                ],
//                "sSwfPath": root_path + "/js/plugins/datatables/extensions/TableTools/swf/copy_csv_xls_pdf.swf"
//            }
            "initComplete": function (settings, json) {
                cacheCouponPack(json);
            },
            "rowCallback": function (row, data, index) {
                $(row).data("id", data.id).addClass("cursor-pointer text-muted");
            }
        });

        function cacheCouponPack(json) {
            if (json.recordsTotal > 0) {
                // 缓存部门列表
                $.map(json.data, function (cp) {
                    couponCache[cp.id] = cp;
                });
            }
        }
        /**
         * 详情展开/关闭
         */
        $('#couponList tbody').on('click', 'td.details-control', function (e) {
            e.preventDefault();
            e.stopPropagation();

            var tr = $(this).closest('tr');
            var row = table.row(tr);

            if (row.child.isShown()) {
                // 关闭详情
                $(this).html('<span class="glyphicons glyphicons-circle_plus text-system cursor-pointer fs14"></span>');
                row.child.hide();
                tr.removeClass('shown');
            }
            else {
                // 展开详情
                $(this).html('<span class="glyphicons glyphicons-circle_minus text-info cursor-pointer fs14"></span>');
                var id = row.data().id, cp = couponCache[id], detail = '<p class="text-center mt20 mb20">尚无满足条件的竞拍品</p>';

                if (cp.placements === undefined) {
                    var members = [];
                    cp.placements = members;
                    cp.openTime = function () {
                        return $.format.date(this.startTime, "yyyy/MM/dd HH:mm");
                    };
                    cp.overTime = function () {
                        return $.format.date(this.endTime, "yyyy/MM/dd HH:mm");
                    };
                    cp.account = function () {
                        return this.hasAccount ? "已开户" : "未开户";
                    };
                    cp.status = function () {
                        var s = sysRewardStatus[this.ticket.status];
                        if (this.ticket.status === 'PAYED') {
                            return '<i class="fa fa-lock text-alert mr5"></i>' + s;
                        } else if (this.ticket.status === 'ALLOCATED') {
                            return '<i class="fa fa-certificate text-warning mr5"></i>' + s;
                        } else if (this.ticket.status === 'QUALIFIED') {
                            return '<i class="fa fa-check-circle text-success mr5"></i>' + s;
                        } else if (this.ticket.status === 'EXPIRED') {
                            return '<i class="fa fa-clock-o text-danger mr5"></i>' + s;
                        }
                        return s;
                    };
                    cp.online = function () {
                        return this.status === 'ONLINE';
                    };
                    cp.offline = function () {
                        return this.status === 'OFFLINE';
                    };
                    cp.bigStatus = function () {
                        switch (this.status)
                        {
                            case "ONLINE":
                                return "上线中";
                                break;
                            case "OFFLINE":
                                return "已下线";
                                break;
                            case "OWNED":
                                return "已拍出";
                                break;
                            case "UNSOLD":
                                return "流拍";
                                break;
                            default:
                                return "未知";

                        }
                    };
                    $.get("pointsystem/listItemByAuction/" + id, function (res) {
                        if (res.recordsTotal > 0) {
                            for (var i = 0; i < res.recordsTotal; i++) {
                                var ticket = res.data[i];
                                members.push(ticket);
                            }
                            if (cp.eventType === 'USER_REGISTER') {
                                detail = sys.render("#couponPlacementTemplate", cp);
                            }else if(cp.eventType === 'USER_INVEST'){
                                detail = sys.render("#investCouponTemplate", cp);
                            }else{
                                detail = sys.render("#refereeCouponTemplate", cp);
                            }
                        }
                        row.child(detail).show();
                        tr.addClass('shown');
                    }).fail(function () {
                        alert("网络通信错误");
                    });
                } else {
                    if (cp.placements.length > 0) {
                        if (cp.eventType === 'USER_REGISTER') {
                            detail = sys.render("#couponPlacementTemplate", cp);
                        }else if(cp.eventType === 'USER_INVEST'){
                            detail = sys.render("#investCouponTemplate", cp);
                        }else{
                            detail = sys.render("#refereeCouponTemplate", cp);
                        }
                    }
                    row.child(detail).show();
                    tr.addClass('shown');
                }
            }
        });

        $('#couponList tbody').on('click', '.edit', function (e) {
            e.preventDefault();
            e.stopPropagation();

            var tid = $(this).data("tid"), btn = $(this);
            location = "pointsystem/itemsAdd/0/" + tid;
        });

        /**
         * 下线
         */
        $('#couponList tbody').on('click', '.pay-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            var tid = $(this).data("tid"), btn = $(this);
            sys.confirm("确定下线该拍品？", function () {
                sys.processModal();
                $.get("pointsystem/offlineAuctionItem/" + tid, function (res) {
                    if (res.success) {
                        var st = document.querySelector('[data-on-tid="' + tid + '"]');
                        var cz = document.querySelector('[data-off-tid="' + tid + '"]');
                        $(st).hide();
                        $(cz).show();
                        $(document.querySelector('[data-status-tid="' + tid + '"]')).html("OFFLINE");
                        alert("拍品已下线");
                        sys.closeModal();
                    } else {
                        alert("拍品下线失败");
                        sys.closeModal();
                    }
                }).fail(function () {
                    alert("网络通信错误");
                    sys.closeModal();
                });
            });
        });

        /**
         * 上线
         */
        $('#couponList tbody').on('click', '.reject-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            var pid = $(this).data("pid"), sort = $(this).data("sort"), tid = $(this).data("tid"), uid = $(this).data("uid"), amount = $(this).data("amount"), btn = $(this);
            
            $.get("pointsystem/countBySortOnline", {"sort": sort,"auctionItemId":tid}, function (result) {
                if (result.success) {
                    alert("拍卖顺序已经存在，无法上线!");
                    return false;
                } else {
                    sys.confirm("确定上线该拍品？", function (btn) {
                        var $btn = $(btn);
                        sys.btnSpin($btn);
                        sys.processModal();
                        var data = {
                            id: tid
                        };
                        $.post("pointsystem/onlineAuctionItem", data, function (res) {
                            if (res.success) {
                                var st = document.querySelector('[data-on-tid="' + tid + '"]');
                                var cz = document.querySelector('[data-off-tid="' + tid + '"]');
                                $(st).show();
                                $(cz).hide();
                                $(document.querySelector('[data-status-tid="' + tid + '"]')).html("ONLINE");
                                alert("拍品上线成功");
                                sys.closeModal();

                            } else {
                                alert("拍品上线失败：" + res.message);
                                sys.btnStop($btn);
                                sys.closeModal();
                            }
                        }).fail(function () {
                            alert("网络通信错误");
                            sys.btnStop($btn);
                            sys.closeModal();
                        });
                    });
                }
            });
        });
    };

    initCouponTable();
});


function setDefault(id) {
    if (confirm('确定默认拍卖活动？')) {
        $.get("pointsystem/setDefault/" + id, function (res) {
            if (res.success) {
                alert(res.message);
                location.reload();
            } else {
                alert("活动状态刷新失败");
            }
        });
    }
    return false;
}